package com.mactivity.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.mactivity.database.ForgotPasswordFunctions;
import com.mactivity.helper.Constants;
import com.mactivity.helper.EncryptionHelper;
import com.mactivity.helper.MailHelper;
import com.mactivity.helper.Messages;
import com.mactivity.helper.RandomPasswordHelper;
import com.mactivity.helper.ValidationsHelper;

/**
 * This class contains all the UI components of the Forgot Password screen and
 * Handles the events that occurs on the various components.
 * 
 * @author Shwetha Narayan
 * 
 */
public class ForgotPasswordActivity extends Activity implements OnClickListener {
	Button buttonCancel;
	Button buttonSendPassword;
	EditText editEmailId;

	/**
	 * This method is acquires the handlers of all the UI components of the
	 * Forgot password screen. This is called on creation of the activity.
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.forgotpassword);

		Log.d(Constants.LOG_FORGOT_PASSWORD_TAG, "Forgot Password created");

		buttonCancel = (Button) findViewById(R.id.buttonCancel);
		buttonSendPassword = (Button) findViewById(R.id.buttonSendPassword);

		editEmailId = (EditText) findViewById(R.id.editForgotPasswordEmail);

		// Attach the onClickListner to the buttons
		buttonCancel.setOnClickListener(this);

		// Attach the onClickListner to the send password button.
		buttonSendPassword.setOnClickListener(this);

	}

	/**
	 * This is the overridden onClick method, of the onClickListner class which
	 * ForgotPassword class implements. This method handles all the onClick
	 * events on the buttons present in the Forgot Password screen.
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.buttonSendPassword:
			// Check if email Id is valid create toast if the email id is
			// invalid
			String emailEntered = editEmailId.getText().toString();
			if (!emailEntered.equals("")) {
				boolean formatValid = ValidationsHelper
						.checkEmailFormat(emailEntered);
				if (formatValid) {
					// If the format is valid, then check if the email Id is
					// registered with the application.
					ForgotPasswordFunctions forgotPassword = new ForgotPasswordFunctions();
					String invalidEmail = forgotPassword
							.validateEmailId(emailEntered);

					// If the email id is registered, then reset the password
					// and send it to the registered email Id.
					if (invalidEmail.equalsIgnoreCase("0")) {
						// Reset the password
						String randomPassword = RandomPasswordHelper
								.createRandomPassword();
						// Create the body of the message with the password.
						String emailMessage = Messages.MAIL_FORGOT_PASSWORD_MSG;
						emailMessage = emailMessage.replaceAll(
								Messages.MAIL_RESET_PASSWORD, randomPassword);
						String emailSubject = Messages.MAIL_FORGOT_PASSWORD_SUBJECT;
						// Replace the password in the database, with the new
						// randomly generated one.
						forgotPassword.resetPassword(emailEntered,
								EncryptionHelper.encrypt(randomPassword));

						// Send the mail to the user
						MailHelper mailHelper = new MailHelper();

						try {
							// Send the mail to the User with the randomly
							// generated password.
							String toEmailId = emailEntered;
							mailHelper.sendMail(toEmailId, emailMessage,
									emailSubject);
						} catch (Exception e) {
							Log.e(Constants.LOGGER_ERROR_TAG,
									"Error occured while sending the mail. "
											+ e.getMessage());
						}

						// Display that the message is sent to the user and
						// return to the Login page.
						Toast.makeText(
								this,
								"Password is reset and is sent to you the Email Id mentioned.",
								Toast.LENGTH_LONG).show();

					} else {
						// if the given email Id is not registered, then give a
						// message to the user that email Id is not registered.
						Toast.makeText(
								this,
								"Email Id is not registered.Please enter a registered Email Id.",
								Toast.LENGTH_LONG).show();
					}

				} else {
					Toast.makeText(this, "Please enter a valid email format.",
							Toast.LENGTH_LONG).show();
				}
			} else {
				Toast.makeText(this, "Please enter an email Id.",
						Toast.LENGTH_LONG).show();
			}

			break;
		case R.id.buttonCancel:
			// Navigate to the Login screen if the user does not want to choose
			// resetting.
			Intent myIntent = new Intent(ForgotPasswordActivity.this,
					LoginActivity.class);
			ForgotPasswordActivity.this.startActivity(myIntent);
			finish();
			break;

		}

	}

	/**
	 * override the back button to make the navigation to the Login page.
	 */
	@Override
	public void onBackPressed() {
		Intent myIntent = new Intent(ForgotPasswordActivity.this, LoginActivity.class);
		ForgotPasswordActivity.this.startActivity(myIntent);
		finish();
	}

}
